package com.meryl.dtk;

import com.intellij.ide.IdeView;
import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.LangDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDirectory;
import com.intellij.psi.impl.file.PsiDirectoryFactory;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.regex.Pattern;

public class CreateControllerAction extends AnAction {

    @Override
    public void actionPerformed(AnActionEvent e) {
        Project project = e.getProject();

        IdeView ideView = e.getRequiredData(LangDataKeys.IDE_VIEW);
        PsiDirectory directory = ideView.getOrChooseDirectory();
        VirtualFile dirPath = directory.getVirtualFile();
        String path = dirPath.getPath();

        String packageName = path.substring(path.indexOf("java") + 5).replace("/", ".");
        String controllerName = Messages.showInputDialog("Controller Name", "Create JDS Controller", Messages.getInformationIcon());
        if (controllerName == null) {
            return;
        }

        if (!packageName.contains("module")) {
            Messages.showErrorDialog("The Jds module is not included in the project. Please create the Jds module first", "Error");
            return;
        }

        String[] split = packageName.split("\\.");
        String moduleName = split[split.length - 2];

        String text = "package " + packageName + ";\n " +
                "\n" +
                "import com.jds.core.controller.JdsController;\n" +
                "import org.springframework.stereotype.Controller;\n" +
                "import org.springframework.web.bind.annotation.RequestMapping;\n" +
                "\n" +
                "@Controller\n" +
                "@RequestMapping(\"/" + moduleName + "/" + (Character.toLowerCase(controllerName.charAt(0)) + controllerName.substring(1)) + "\")\n" +
                "public class " + controllerName + "Controller extends JdsController {\n" +
                "}\n";


        WriteCommandAction.runWriteCommandAction(project, () -> {
            try {
                PsiDirectoryFactory.getInstance(project)
                        .createDirectory(dirPath)
                        .createFile(controllerName + "Controller.java")
                        .getVirtualFile()
                        .setBinaryContent(text.getBytes(StandardCharsets.UTF_8));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
    }
}
